<?php

// Europa 100 AD

// General Functions


# Return Date & Time
function return_datetime($time = 0)
{
    // set the time to the current time if none was passed on
    if ($time == 0){
            return date('D, j M y -  G:i:s');
    } else {
            return date('D, j M y -  G:i:s', $time);
    }
    
}

# Output/buffer compression function to be worked on (perhaps)
function write($add_to_buffer){
    global $buffer;
    $buffer .= $add_to_buffer;
}

# Log and display all errors
function game_error($error_code){

// TODO - log errors to database or txt file
    switch ($error_code){
        case 'NF':
            echo '<b><font color=red>Error. This section of the game isn\'t available to play at the moment.</font></b>'; 
          break;
        case 'NP':
            echo '<b><font color=red>Error. What almost occured shouldn\'t be possible.</font></b>'; 
          break;
        case '403':
            echo '<b><font color=red>Forbidden. This section of the game isn\'t available to your account. A log of this error has been created and sent to game administration.</font></b>'; 
          break;
        default:
            echo '<b><font color=red>Error.</font></b>'; 
    }
}



// OBSOLETE FUNCTION
// causes (variable) problems when used with PHP5
function load_page($step){
    global $config, $db;
    
    $sql = "SELECT * FROM `core_locations` WHERE `alias`='$step'";
    
    $res = $db->query($sql);
    //printf("Select returned %d rows.\n", $res->num_rows);
    
    $row = $res->fetch_assoc();
    $checked_step = $row['location'];
    if (strlen($checked_step) > 0)
    {
        if (strlen($row['title']) > 0){
                echo '<h1>'. $row['title'] . '</h1>';
                echo '<p>';
                require($config['dir_inc'] . $checked_step);
                echo '</p>';
            } else {
                echo '<p>';
                require($config['dir_inc'] . $checked_step);
                echo '</p>';
            }
        
        return true;
    }
    else
    {
        game_error('NF');
        return false;
    }  
    
}


# Display in-game links to other in-game pages
function ahref($location,$title,$extra = '')
{
	global $config, $uid;
	return '<a href=' . $config['url']['play'] . $uid . $location . ' '.$extra.'>' . $title . '</a>';
}

# Function that takes in an array of options a player has on a page and displays them nice and neatly
function player_options ($options = array(), $nolink=0)
{
    $output = '';
	foreach ($options as $k => $v) {
	    if ($nolink == 0){
	        $output .= '<li>' . ahref($k,$v);
	    } else {
	        $output .= '<li>' . $v;
	    }
	}
	$output .= '';
	return $output;
}

# Form display function
// TODO require work to make it more useful
function html_form($location, $input, $form_name='europa100ad')
{
    global $config, $uid;
    $form_buffer = '<form action="'.$config['url']['play'] . $uid . $location . '" name="' . $form_name .'" method="post">';
    $form_buffer .= $input;
    $form_buffer .= '</form>';
    
    return $form_buffer;
}

# Function created to help simplize in-game currency transactions (from user to government/computer) and log them for admin monitoring
// TODO - log the transactions
function transfer_money_user2computer($source,$destination,$amount,$currency)
{
    global $db,$error_message;
    $currency = strtolower($currency);

    // $destination should look like:
    // $destination = array('table' => $table,'assoc_id' => $account_id,'account_name' => $account_name);

    // $source should look like:
    // $source = array('assoc_id' => $user_id,'username' => $username);

    $error_message = '';
    # (check if $user_info is already loaded and use it if it is... else:)
    # Check there is enough at source
    $source_id = $source['assoc_id'];
    $destination_id = $destination['assoc_id'];
    $source_username = $source['username'];
    $destination_name = $destination['account_name'];
    $money_in_hand = $db->return_first_result("SELECT $currency FROM `user_finances` WHERE `assoc_id`='$source_id'");
    $money_available = $money_in_hand[$currency];
    if ($money_available > 0)
    {
        # (Check the destination is a valid place)
        # Update both mysql records
        
        # take money away from source
        $sql = "UPDATE `user_finances` SET `$currency` = `$currency`-'$amount' WHERE `assoc_id` ='$source_id'";
        $db->query($sql);
       // echo '<br>'.$sql;
        # give money to destination
        $sql = "UPDATE `".$destination['table']."` SET `$currency` = `$currency`+'$amount' WHERE `assoc_id` ='$destination_id'";
        $db->query($sql);
        echo "<Br>$source_username has enough money ($money_available) to give to $destination_name - which is only $amount<br>";
        return true;
    }
    else
    {
        $error_message = "$source_username doesn't have enough money in hand";
        return false;
    }
}



# Function created to help simplize in-game currency transactions (from user to government/computer) and log them for admin monitoring
// TODO - log the transactions
function transfer_money_user2user($source,$destination,$amount,$currency)
{
    global $db,$error_message;
    $currency = strtolower($currency);

    $error_message = '';
    # (check if $user_info is already loaded and use it if it is... else:)
    # Check there is enough at source

    $money_in_hand = $db->return_first_result("SELECT $currency FROM `user_finances` WHERE `assoc_id`='$source'");
    $money_available = $money_in_hand[$currency];
    if ($money_available > 0)
    {
        # (Check the destination is a valid place)
        # Update both mysql records
        
        # take money away from source
        $sql = "UPDATE `user_finances` SET `$currency` = `$currency`-'$amount' WHERE `assoc_id` ='$source'";
        $db->query($sql);
       // echo '<br>'.$sql;
        # give money to destination
        $sql = "UPDATE `user_finances` SET `$currency` = `$currency`+'$amount' WHERE `assoc_id` ='$destination'";
        $db->query($sql);
        //echo "<Br>$source_username has enough money ($money_available) to give to $destination_name - which is only $amount<br>";
        return true;
    }
    else
    {
        $error_message = "$source_username doesn't have enough money in hand";
        return false;
    }
}





# Function created to help simplize in-game currency transactions (from governemtn to user) and log them for admin monitoring
// TODO - log the transactions
function transfer_money_gov2user($source,$destination,$amount,$currency)
{
    global $db,$error_message;
    $currency = strtolower($currency);

    $error_message = '';
    $fund_info = $db->return_first_result("SELECT name,$currency FROM `government_money` WHERE `assoc_id`='$source'");
    $fund_name = $fund_info['name'];
    $money_available = $fund_info[$currency];
    if ($money_available > 0)
    {
        # (Check the destination is a valid place)
        # Update both mysql records
        
        # take money away from source
        $sql = "UPDATE `user_finances` SET `$currency` = `$currency`+'$amount' WHERE `assoc_id` ='$destination'";
        $db->query($sql);
       // echo '<br>'.$sql;
        # give money to destination
        $sql = "UPDATE `government_money` SET `$currency` = `$currency`-'$amount' WHERE `assoc_id` ='$source'";
        $db->query($sql);
        //echo "<Br>$amount transfered from $fund_name to you<br>";
        return true;
    }
    else
    {
        $error_message = "$fund_name doesn't have enough money";
        return false;
    }
}

# Item transfer monitoring and standardization
// TODO be developed
function transfer_item($source,$destination,$item,$quantity)
{
	// $source = array('table','assoc_id');
	// $destination = array('table','assoc_id');
	
    global $db,$error_message;
    $currency = strtolower($currency);

    $error_message = '';
    # (check if $user_info is already loaded and use it if it is... else:)
    # Check there is enough at source

    $source_id = $source['assoc_id'];
    $source_table = $source['table'];
    $source_id = $source['assoc_id'];
    $source_table = $source['table'];
    $source_info = $db->return_first_result("SELECT * FROM `$source_table` WHERE `item`='$item' AND assoc_id`='$source_id'");

    if ($source_info['quantity'] >= $quantity)
    {
        # (Check the destination is a valid place)
        # Update both mysql records
        
        # take money away from source
        $sql = "UPDATE `$source_table` SET `quantity` = quantity-'$quantity' WHERE `item`='$item' AND `assoc_id` ='$source_id'";
        $db->query($sql);
       // echo '<br>'.$sql;
        # give money to destination
        $sql = "UPDATE `$destination_table` SET `quantity` = quantity+'$quantity' WHERE `item`='$item' AND `assoc_id` ='$destination_id'";
        $db->query($sql);
        return true;
    }
    else
    {
        $error_message = "Not enough items available to transfer.";
        return false;
    }
}

# function that will load a governemnt editable game setting set in the database (`government_settings`)
function government_setting($setting)
{
    global $db;
        //$test = $db->return_first_result("SELECT * FROM user_sleep");
        //echo $test['assoc_id'];
        $gov_info = $db->return_first_result("SELECT `data` FROM `government_settings` WHERE `field`='$setting'");
    return $gov_info['data'];
}

# function that will load a governemnt password for a section of teh game
function government_password($zone)
{
    global $db;
        //$test = $db->return_first_result("SELECT * FROM user_sleep");
        //echo $test['assoc_id'];
        $gov_info = $db->return_first_result("SELECT `password` FROM `government_passwords` WHERE `zone`='$zone'");
    return $gov_info['password'];
}



function get_item($user_id, $item,$quantity,$section,$type,$exp = 0,$quality = 0, $purchase_location = ''){
    global $db, $config;
    
    $sql = "SELECT * FROM `user_items` WHERE `assoc_id`='$user_id' AND `item`='$item'";
    if($res = $db->query($sql))
    {
        $num_rows = $res->num_rows;
        if ($num_rows > 0 && $exp == 0)
        {
            $sql = "UPDATE `user_items` SET `quantity` = quantity+'$quantity' WHERE `assoc_id` = '$user_id' AND `item`='$item' LIMIT 1";
            return $db->query($sql);
        }
        else
        {
            $sql = "INSERT INTO `user_items` (`assoc_id`, `item`, `section`, `type`, `quantity`,`exp`,`quality`,`purchase_location`) VALUES ('$user_id','$item','$section','$type','$quantity','$exp','$quality','$purchase_location')";
            return $db->query($sql);
        }
    }    
 }







# function to neatly display a variables content
function display_var_old($var)
{
    echo '<br>--<pre>';
    echo print_r($var);
    echo '</pre><BR>';
}




function display_var( $TheArray )
  { // Note: the function is recursive
    echo "<table border=1>\n";
    
    $Keys = array_keys( $TheArray );
    foreach( $Keys as $OneKey )
    {
      echo "<tr>\n";
      
      echo "<td bgcolor='#727450'>";
      echo "<B>" . $OneKey . "</B>";
      echo "</td>\n";
      
      echo "<td bgcolor='#C4C2A6'>";
        if ( is_array($TheArray[$OneKey]) )
          display_var($TheArray[$OneKey]);
        else
          echo $TheArray[$OneKey];
      echo "</td>\n";
      
      echo "</tr>\n";
    }
    echo "</table>\n";
  }

  
 function dice_throw($value, $max = 100)
 {
 	$rand = mt_rand(0,$max);
 	
 	if ($rand <= $value)
 	{
 		return true;
 	}
 	else 
 	{
 		return false;
 	}
 }
 
 function div_scroll_to_bottom($div_name)
 {
 	$output = "<script type=\"text/javascript\">
	                   
	var objDiv = document.getElementById(\"$div_name\");
	
	var test1 = objDiv.scrollHeight;
	var test2 = objDiv.offsetHeight;
	if (test1 > 0) // all but Explorer Mac
	{
		objDiv.scrollTop = objDiv.scrollHeight;
	}
	else // Explorer Mac;
	     //would also work in Explorer 6 Strict, Mozilla and Safari
	{
		objDiv.scrollTop = objDiv.offsetHeight;
	}
	
	</script>";
 	return $output;
 }
  
 
 
 
 
 
 function display_text($file)
 {
 	$lines = file(DIR_TEXT . $file . '.txt');
    return $lines[mt_rand(0,count($lines)-1)];
 }
 
 
 
 
 
 
 function player_lookup_db($assoc_id)
 {
 	// display a players name and link from their id
 	echo 'db player lookup';
 	
 }
 
 
 
 
 
 
 
 function player_lookup($id,$name)
 {
 	return ahref("/psearch/$id/",$name);
 }
 
 
 
 
 
 
 
 function populate_quantity_box($name, $quantity, $postfix = '', $selected = '', $order = 'ASC', $other = '')
 {
 	$output = '';
 	
 	$output .= "<select name=$name $other>";
 	
 	if ($order == 'ASC')
 	{ 
 		for ( $counter = 1; $counter <= $quantity; $counter++ )
 		{
 			if ($counter == $selected) { $select = ' SELECTED="yes" '; } else { $select = ' '; }
 			$output .= "<option value=\"$counter\" $select >$counter $postfix</option>";
 		}
 	}
 	else 
 	{
 		for ( $counter = $quantity; $counter >= 1; $counter-- )
 		{
 			if ($counter == $selected) { $select = ' SELECTED="yes" '; } else { $select = ' '; }
 			$output .= "<option value=\"$counter\" $select >$counter $postfix</option>";
 		}
 	}
 	
 	
 	
 	$output .= "</select>";
 	
 	return $output;
 }
 
 
 function log_memory($string = '')
 {
 	global $log_buffer;
 	
 	//echo "<pre>$string</pre>";
 	
 	if (strlen($log_buffer) < 1)
 	{
 		$log_buffer = '<UL>';
 	}
 	
 	if (strlen($string) < 1)
 	{
 		return $log_buffer . '</UL>';
 	}
 	else 
 	{
 		
            $myFile = DIR_LOG.date("Ymd").".txt";
			$fh = fopen($myFile, 'a') or die("can't open file");
			$stringData = "\n $string\n";
			fwrite($fh, $stringData);
			fclose($fh);
 		@$log_buffer .= '<li>'.$string;
 		return true;
 	}
 }
 
 function government_zone($zone, $guess_pass = '')
 {
 	// this page is password protected for government use only
 	
 	$correct_password = government_password('$zone');
 	
 	if ($guess_pass == '')
 	{
 		// prompt for the password as the user hasn't submitted any
 		
 		# store the current location in database
 		
 		# send the user to the password page
 		
 		return false;
 	}
 	elseif ($guess_pass == $correct_password)
 	{
 		// password is correct
 		return true;
 	}
 	elseif ($guess_pass != $correct_password)
 	{
 		// password is wrong
 		
 		# log the user, time and guessed_password
 		
 		# send the user to an access denied page
 		return false;
 	}
 	
 }
 
 
 function gladiator_item_lookup($lookup_id)
{
    global $db;
        //$test = $db->return_first_result("SELECT * FROM user_sleep");
        //echo $test['assoc_id'];
    $gov_info = $db->return_first_result("SELECT `name` FROM `gladiator_items` WHERE `id`='$lookup_id'");
    return $gov_info['name'];
}
?>